﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebDownloader
{
    public static class Functions
    {

        public static string GetSource(string pURL, System.Text.Encoding pEncoding)
        {
            string tResult = "";

            for (int i = 0; i <= 5; i++)
            {
                try
                {
                    var tRequest = System.Net.HttpWebRequest.Create(pURL);

                    using (var tResponse = tRequest.GetResponse())
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(tResponse.GetResponseStream(), pEncoding))
                        {
                            tResult = sr.ReadToEnd();
                        }
                    }


                    break;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("retry(" + i.ToString() + ") " + ex.ToString());
                }
            }
            return tResult;
        }


        public static string DownloadFile(string SourceLink, string DestFileName)
        {
            string tMessage = "";

            System.Net.WebClient wc = new System.Net.WebClient();
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    tMessage = "";

                    if (!System.IO.File.Exists(string.Format(@".\Completed\{0}", DestFileName)))
                    {
                        wc.DownloadFile(SourceLink, string.Format(@".\downloading\{0}", DestFileName));

                        System.IO.File.Move(string.Format(@".\downloading\{0}", DestFileName), string.Format(@".\Completed\{0}", DestFileName));

                        break;
                    }
                    else
                    {
                        break;
                    }
                    
                }
                catch (Exception ex)
                {
                    tMessage = ex.Message;

                    if (System.IO.File.Exists(string.Format(@".\downloading\{0}", DestFileName)))
                        System.IO.File.Delete(string.Format(@".\downloading\{0}", DestFileName));
                }
            }

            if (tMessage.Length > 0 && System.IO.File.Exists(string.Format(@".\downloading\{0}", DestFileName)))
                System.IO.File.Delete(string.Format(@".\downloading\{0}", DestFileName));

            return tMessage;

        }
    }
}
